#include "Player.h"

CPlayer::CPlayer(HGE* hge, size_t x, size_t y)
:m_pSelf(NULL), m_pLeaf(NULL)
{
	if(hge)
	{
		m_pSelf = new CMapUnit(hge,PERSON_PNG,x,y,true);
		m_pSelf->SetZBuffer(LEVEL_2);

		m_pLeaf = new CMapUnit(hge,LEAF_PNG,x,y,true);
		m_pLeaf->SetZBuffer(LEVEL_3);
		SetDirection(DIR_STOP);
	}
}

CPlayer::~CPlayer(void)
{
	if(m_pSelf)
		delete m_pSelf;
	m_pSelf = NULL;
}

bool CPlayer::DoFrame( float dt )
{
	if(m_pSelf == NULL)
		return false;

	float x = m_pSelf->GetX();
	float y = m_pSelf->GetY();
	float move = SPEED*dt;

	switch(m_direction)
	{
	case DIR_UP:
		{
			y -= move;
			if(y < GRID_Y)
				m_direction = DIR_DOWN;
			m_pLeaf->SetShow(true);
		}
		break;
	case DIR_DOWN:
		{
			y += move;
			if(y > GRID_Y + (UNIT_ROW-1)*UNIT_H)
				m_direction = DIR_UP;
			m_pLeaf->SetShow(true);
		}
		break;
	case DIR_LEFT:
		{
			x -= move;
			if(x < GRID_X)
				m_direction = DIR_RIGHT;
			m_pLeaf->SetShow(true);
		}
		break;
	case DIR_RIGHT:
		{
			x += move;
			if(x > GRID_X + (UNIT_COL-1)*UNIT_W)
				m_direction = DIR_LEFT;
			m_pLeaf->SetShow(true);
		}
		break;
	default:
		m_pLeaf->SetShow(false);
		break;
	}
	m_pSelf->SetPosition(x,y);
	m_pLeaf->SetPosition(x,y);

	return false;
}

bool CPlayer::DoRender()
{
	if(m_pLeaf)
		m_pLeaf->DoRender();
	if(m_pSelf)
		m_pSelf->DoRender();

	return false;
}

hgeRect CPlayer::GetEyeShot()
{
	float x1 = m_pSelf->GetX()-EYESHOTX;
	float y1 = m_pSelf->GetY()-EYESHOTY;
	float x2 = m_pSelf->GetX()+EYESHOTX+UNIT_W;
	float y2 = m_pSelf->GetY()+EYESHOTY+UNIT_H;

	x1 -= GRID_X;
	x2 -= GRID_X;
	y1 -= GRID_Y;
	y2 -= GRID_Y;

	if(x1 < 0)
		x1 = 0;
	if(y1 < 0)
		y1 = 0;
	if(x2 > GRID_W)
		x2 = GRID_W;
	if(y2 > GRID_H)
		y2 = GRID_H;

	hgeRect rect(x1,y1,x2,y2);
	return rect;
}

void CPlayer::OnStop( float x, float y )
{
	m_direction = DIR_STOP;
	m_pSelf->SetPosition(x,y);
}

void CPlayer::MoveTo( float x, float y )
{
	m_pSelf->SetPosition(x,y);
	m_pLeaf->SetPosition(x,y);
}

void CPlayer::SetDirection( int dir )
{
	m_direction = dir;
	float x = m_pSelf->GetX();
	float y = m_pSelf->GetY();

	switch(m_direction)
	{
	case DIR_UP:
		y -= UNIT_H;
		break;
	case DIR_DOWN:
		y += UNIT_H;
		break;
	case DIR_LEFT:
		x -= UNIT_W;
		break;
	case DIR_RIGHT:
		x += UNIT_W;
		break;
	default:
		break;
	}

	MoveTo(x,y);
}